package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.*;
import com.leyou.item.pojo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author CHERRY
 * @date 2018-09-04-21:11
 */
@Service
public class GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private SpuDetailMapper spuDetailMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private StockMapper stockMapper;

    /**
     * 分页查询SPU
     *
     * @param key      搜索词
     * @param saleable 是否上架
     * @param page     当前页码
     * @param row      每页显示行数
     * @return 分页信息
     */
    public PageResult querySpuByPage(String key, Boolean saleable, Integer page, Integer row) {

        //创造查询条件
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        //商品有效
        criteria.andEqualTo("valid", true);
        //搜索词不为空 模糊查询
        if (StringUtils.isNotBlank(key)) {
            criteria.andLike("title", "%" + key + "%");
        }
        //添加是否上架条件
        if (saleable != null) {
            criteria.andEqualTo("saleable", saleable);
        }
        //分页插件 限制最大查询100条
        PageHelper.startPage(page, Math.min(row, 100));
        //通用mapper执行分页查询
        List<Spu> spus = this.goodsMapper.selectByExample(example);
        PageInfo pageInfo = new PageInfo(spus);

        List<SpuBo> spuBos = new ArrayList<>();
        spus.forEach(spu -> {
            SpuBo spuBo = new SpuBo();
            BeanUtils.copyProperties(spu, spuBo);
            //查询品牌 得到品牌名称
            Brand brand = this.brandMapper.selectByPrimaryKey(spu.getBrandId());
            spuBo.setBname(brand.getName());
            //调用CategoryService 根据多个id查询名称
            List<String> names = this.categoryService.queryCategoryNamesByIds(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
            //拼接商品分类名称，并封装
            spuBo.setCname(StringUtils.join(names, "/"));
            spuBos.add(spuBo);
        });
        return new PageResult(pageInfo.getTotal(), spuBos);
    }

    /**
     * 新增商品
     *
     * @param spu
     */
    @Transactional
    public void saveSpuDetail(SpuBo spu) {
        //新增spu数据
        spu.setValid(true);
        spu.setSaleable(true);
        spu.setCreateTime(new Date());
        spu.setLastUpdateTime(spu.getCreateTime());
        this.goodsMapper.insertSelective(spu);
        //新增spu_detail数据
        SpuDetail spuDetail = spu.getSpuDetail();
        //主键回写 spuId
        spuDetail.setSpuId(spu.getId());
        this.spuDetailMapper.insertSelective(spuDetail);
        //保存sku和stock 库存数据
        saveSkuAndStock(spu.getSkus(), spu.getId());

    }

    /**
     * 保存sku和库存数据
     *
     * @param skus  sku集合
     * @param spuId 新增的spu 主键id
     */
    private void saveSkuAndStock(List<Sku> skus, Long spuId) {
        for (Sku sku : skus) {

            //新增sku数据
            //使用回写的spu_id
            sku.setSpuId(spuId);
            sku.setCreateTime(new Date());
            sku.setLastUpdateTime(sku.getCreateTime());
            this.skuMapper.insertSelective(sku);
            //添加stock数据
            Stock stock = new Stock();
            stock.setSkuId(sku.getId());
            stock.setStock(sku.getStock());
            this.stockMapper.insertSelective(stock);
        }
    }

    /**
     * 根据spuId查询商品详情
     *
     * @param spuId
     * @return
     */
    public SpuDetail querySpuDetailBySpuId(Long spuId) {
        return this.spuDetailMapper.selectByPrimaryKey(spuId);
    }

    /**
     * 根据spuId商品集合
     *
     * @param spuId
     * @return
     */
    public List<Sku> querySkusBySpuId(Long spuId) {
        List<Sku> skus = this.goodsMapper.querySkusBySpuId(spuId);
        return skus;
    }

    /**
     * 修改商品详情
     *
     * @param spuBo
     */
    @Transactional
    public void editSpuDetail(SpuBo spuBo) {
        //删除stock数据
        Sku sku = new Sku();
        sku.setSpuId(spuBo.getId());
        //根据spuId查询需要删除的sku
        List<Sku> skuList = this.skuMapper.select(sku);
        //遍历根据skuId删除, 多次操作数据库 。。
        /*skuList.forEach(dSku -> {
            this.stockMapper.deleteByPrimaryKey(dSku.getId());
        });*/
        //旧的sku存在 ，删除
        if (!CollectionUtils.isEmpty(skuList)) {

            List<Long> ids = skuList.stream().map(dSku -> dSku.getId()).collect(Collectors.toList());
            //通用mapper
            Example example = new Example(Stock.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andIn("skuId", ids);
            this.stockMapper.deleteByExample(example);
            //删除sku数据
            this.skuMapper.delete(sku);
        }

        //更新spu数据
        Spu spu = new Spu();
        BeanUtils.copyProperties(spuBo, spu);
        spu.setLastUpdateTime(new Date());
        this.goodsMapper.updateByPrimaryKeySelective(spu);
        //更新spu_detail数据
        SpuDetail spuDetail = spuBo.getSpuDetail();
        //设置主键
        spuDetail.setSpuId(spuBo.getId());
        this.spuDetailMapper.updateByPrimaryKeySelective(spuDetail);
        //添加sku和stock数据
        saveSkuAndStock(spuBo.getSkus(), spuBo.getId());
    }

    /**
     * 根据Id查询spu
     *
     * @param id
     * @return
     */
    public Spu querySpuById(Long id) {
        return this.goodsMapper.selectByPrimaryKey(id);
    }
}
